package com.wlz.service.impl;

import com.wlz.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Administrator
 * @date ：2018/10/25/025 16:06
 */


public class BaseImpl {
    Logger logger = LoggerFactory.getLogger(BaseImpl.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Autowired
//    private UserService userService;


    /**
     * 获取属性值不为空的度数
     *
     * @param request 对象请求
     * @return 度数
     */
    int getObjectPropertyValueNotNullCount(Object request) {

//        属性值不为空的计数器
        int count = 0;
//        属性计算器
        int sbNameCount = 0;

        StringBuilder sbName = new StringBuilder();
        StringBuilder sbValue = new StringBuilder();
        String[] fieldNames = getFiledName(request);

        //遍历所有属性
        for (String fieldName : fieldNames) {
            sbNameCount++;
            //获取属性的名字
            Object value = getFieldValueByName(fieldName, request);
            sbName.append(fieldName);
            sbValue.append(value);

            logger.info("属性名:>>>>>" + fieldName + ">>>>>>属性值:>>>>>>>" + value);
            logger.info("属性名:>>>>>" + sbName.toString() + ">>>>>>属性值:>>>>>>>" + sbValue.toString());
            System.out.println("属性名:>>>>>" + fieldName + ">>>>>>属性值:>>>>>>>" + value);

            if (!StringUtils.isEmpty(value)) {
                count++;
            }

        }

        int ratio = 100 / sbNameCount;

        int degree = count * ratio;
        if (count == fieldNames.length) {
            degree = 100;
        }


        return degree;
    }


    /**
     * 根据属性名获取属性值
     *
     * @param fieldName 属性名
     * @param o         对象
     * @return 对象
     */
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter);
            return method.invoke(o);
        } catch (Exception e) {

            return null;
        }
    }

    /**
     * 获取属性名数组
     */
    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }


    /**
     * 获取存放在Header里面的tokenID
     *
     * @param request 网络请求
     * @return tokenID
     */
    protected Map<String, Object> getUserIdByTokenID(HttpServletRequest request) {
        Map<String, Object> idMap = new HashMap<>();
        String tokenId = request.getHeader("tokenID");
//        String tokenId = "1248f0551499a89f21071954b2d91c8d";
        if (tokenId != null) {
            logger.info("token>>"+tokenId);
            Integer userId = null;
            String token = stringRedisTemplate.opsForValue().get(Constants.LOGIN_TOKEN + tokenId);
            if ("null".equals(token)) {
                stringRedisTemplate.delete(Constants.LOGIN_TOKEN + tokenId);
//                userId = userService.getUserIdByTokenID(tokenId);
                stringRedisTemplate.opsForValue().set(Constants.LOGIN_TOKEN + tokenId, String.valueOf(userId));
            } else {
                if (token != null) {
                    userId = Integer.parseInt(token);
                }
            }
            idMap.put("tokenID", tokenId);
            idMap.put("userId", userId);
        }else {
            idMap.put("tokenID", null);
            idMap.put("userId", null);
        }
        return idMap;
    }


    /**
     * 返回用户的id
     *
     * @param tokenID 用户标识
     * @return 用户的id
     */
    Integer getUserId(String tokenID) {
        Integer userId;

        String loginToken = stringRedisTemplate.opsForValue().get(Constants.LOGIN_TOKEN + tokenID);

        if (StringUtils.isEmpty(loginToken)) {
            return null;
        } else {
            userId = Integer.parseInt(loginToken);
        }
        return userId;
    }


}
